package com.zhz.thymeleafdemo.web.controller;

import com.zhz.thymeleafdemo.pojo.User;
import com.zhz.thymeleafdemo.service.UserService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

@Controller
public class LoginController {
    @Resource
    private UserService userService;

    @GetMapping("login")
    public String login(){
        return "login";
    }

    @PostMapping("/login")
    public String doLogin(@RequestParam("username")String username,
                          @RequestParam("password")String password, HttpServletRequest request){
        User user = userService.getUserByName(username);
        if (user == null) {
            request.setAttribute("msg", "用户名不存在！");
            return "login";
        } else if (!password.equals(user.getPassword())) {
            request.setAttribute("msg", "密码不正确，请确认后再输入！");
            return "login";
        } else {
            request.getSession().setAttribute("loginUser", user);
            return "redirect:/user/toIndex";  //登录成功后重定向到首页。
        }
    }
}
